import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:self32/event/inventory_event.dart';
import 'package:self32/event/set_eas_event.dart';
import 'package:self32/widget/model/qr_model.dart';
import 'package:self32/widget/model/result_model.dart';
import '../entity/book_entity.dart';
import '../event/scan_event.dart';
import '../event/write_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../socket/socket_manager.dart';
import '../util/analysis_book_rule.dart';
import '../util/timer_manager.dart';
import '../widget/app_bar.dart';
import '../widget/custom_floating_action_button_location.dart';
import '../widget/float_button.dart';
import '../widget/model/borrow_return_model.dart';
import '../widget/model/scan_model.dart';

class Return extends StatefulWidget {
  const Return({Key? key}) : super(key: key);

  @override
  State<Return> createState() => _ReturnState();
}

class _ReturnState extends State<Return> {

  BorrowReturnModel model = BorrowReturnModel();
  ResultModel resultModel = ResultModel();

  final List<BookEntity> _bookList = [];


  SocketManager manager = SocketManager();
  var step = 1;
  // StreamSubscription? userSubscription;
  StreamSubscription? inventorySubscription;
  StreamSubscription? easSubscription;
  StreamSubscription? scanSubscription;
  StreamSubscription? writeSubscription;

  final TextEditingController _controller = TextEditingController();
  final FocusNode _focusNode = FocusNode();
  final FocusNode _focusNode2 = FocusNode();

  @override
  initState() {
    super.initState();

    tts.speak('请放置图书');

    Future.delayed(const Duration(seconds: 1),(){
      FocusScope.of(context).requestFocus(_focusNode);
    });


    easSubscription = eventFactory.on<SetEasEvent>().listen((event) {
      if(event.isSuccess!){
        _return(event.no);
      }else{
        _setEasFail(event.no);
      }
    });

    writeSubscription = eventFactory.on<WriteEvent>().listen((event) {
      if(event.isSuccess!){
        _return(event.no);
      }else{
        _setEasFail(event.no);
      }
    });

    scanSubscription = eventFactory.on<ScanEvent>().listen((event) {
      _controller.clear();
      FocusScope.of(context).requestFocus(_focusNode);
      if(event.no == null){
        return;
      }
      if(step == 1){
        setState(() {
          step = 2;
        });
      }
      var bookNo = event.no;
      var element = _bookList.firstWhereOrNull((element) => element.no == bookNo);
      if(element == null){
        findBook(bookNo).then((value){
          if(value != null){
            if(value.stateValue == 'borrowed'){
              value.state = 0;
            }else{
              value.state = 2;
            }
            value.isQr = true;
            value.isScan = true;
            value.force = true;
            value.uid = null;
            _bookList.add(value);
            model.upDataList(_bookList.where((element) => element.isScan == true));
          }
        });
      }
    });


    inventorySubscription = eventFactory.on<InventoryEvent>().listen((event) {
      for(var item in _bookList){
        if(!item.force){
          item.isScan = false;
        }
      }
      if(event.data!=null && event.data!.isNotEmpty){
        if(step == 1){
          setState(() {
            step = 2;
          });
        }
        for(var item in event.data!.toList()){
          String? data;
          if(settingEntity.isUltra!){
            data = item.epc;
          }else{
            data = item.blockData;
          }
          if(data == null){
            continue;
          }
          try{
            var bookNo = analysisBookRule(data);
            var element = _bookList.firstWhereOrNull((element) => element.no == bookNo);
            if(element == null){
              findBook(bookNo).then((value){
                if(value != null){
                  if(value.stateValue == 'borrowed'){
                    value.state = 0;
                  }else{
                    value.state = 2;
                  }
                  value.isScan = true;
                  if(settingEntity.isUltra!){
                    value.uid = item.epc;
                  }else{
                    value.uid = item.uid;
                  }
                  _bookList.add(value);
                  model.upDataList(_bookList.where((element) => element.isScan == true));
                }
              });
            }else{
              element.isScan = true;
              model.upDataList(_bookList.where((element) => element.isScan == true));
            }
          }catch(e){
            model.upDataList(_bookList.where((element) => element.isScan == true));
           print(e);
          }
        }
      }else{
        model.upDataList(_bookList.where((element) => element.isScan == true));
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        currentTask.clear();
        timer.cancel();
        manager.setMode(Mode.none);
        Get.back();
      });
    });

    try{
      if(!settingEntity.qr!){
        manager.setModeAndStart(Mode.inventoryHfRfid);
      }
    }catch(e){
      print(e);
    }

  }
  _setEasFail(no){
    BookEntity? item = _bookList.firstWhereOrNull((element) => element.no == no);
    if(item != null){
      item.state = -1;
      item.error = '防盗位改写失败';
    }
    _setEas();
  }

  _return(no) async {
    var result = await bookReturn(no);
    BookEntity? item = _bookList.firstWhereOrNull((element) => element.no == no);
    if(item != null){
      setState(() {
        if(result.$1 == 200){
          item.state = 1;
        }else{
          item.state = -1;
          item.error = result.$2;
        }
      });
    }
    _setEas();
  }

  _setEas(){
    for(var item in _bookList){
      if(item.isQr && item.state == 0){
        _return(item.no);
        return;
      }
      if(item.uid == null){
        continue;
      }

      if(item.state == 0){
        manager.eas(item.uid!, item.no, false);
        return;
      }
    }
    resultModel.setAble();
    // ResultDialog().show(_bookList.where((element) => element.state==1).length,_bookList.where((element) => element.state == -1).length,(){
    //   resultModel.setAble();
    // });

  }

  _step(){
    return Align(child: Image.asset("assets/images/return_step$step.png",height:46.h,fit: BoxFit.fitHeight,));
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w,bottom: 10.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            InkWell(
              onTap: (){
                currentTask.clear();
                timer.cancel();
                manager.setMode(Mode.none);
                Get.back();
              },
              child: Image.asset("assets/images/back.png", width: 40.w, fit: BoxFit.fitWidth,),
            ),
            Text("图书归还",style: TextStyle(color: Colors.white,fontSize: 12.sp,fontWeight: FontWeight.bold),),
            Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),))
          ],
        )
    );
  }


  @override
  void dispose() {
    // userSubscription?.cancel();
    // userSubscription = null;
    writeSubscription?.cancel();
    writeSubscription = null;
    inventorySubscription?.cancel();
    inventorySubscription = null;
    easSubscription?.cancel();
    easSubscription = null;
    scanSubscription?.cancel();
    scanSubscription = null;
    _controller.dispose();
    FocusScope.of(context).requestFocus(_focusNode2);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        floatingActionButton:floatButton(),
        floatingActionButtonLocation:CustomFloatingActionButtonLocation(
            FloatingActionButtonLocation.endFloat, 0,-60.h),
        body: Stack(
          children: [
            InkWell(
              onTap: (){
                FocusScope.of(context).requestFocus(_focusNode2);
              },
              child: Container(
                  width: double.infinity,
                  height: double.infinity,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      fit: BoxFit.fill,
                      image: AssetImage(
                        "assets/images/bg.png",
                      ),
                    ),
                  ),
                  child: Column(
                    children: [
                      appBar(focus: false),
                      _title(),
                      _step(),
                      if(step == 1)...[
                        SizedBox(height:20.h),
                        if(settingEntity.qr!)...[
                          QrModel().show(_controller,_focusNode),
                          SizedBox(height:10.h),
                        ],
                        ScanModel().show(),
                      ],
                      if(step == 2)...[
                        SizedBox(height:20.h),
                        if(settingEntity.qr!)...[
                          QrModel().show(_controller,_focusNode),
                          SizedBox(height:10.h),
                        ],
                        model.show(_bookList,1,() async {
                          manager.setModeAndStart(Mode.none);
                          _bookList.removeWhere((element) => element.isScan == false);
                          _setEas();
                          setState(() {
                            step = 3;
                          });
                        }),
                      ],
                      if(step == 3)...[
                        SizedBox(height:20.h),
                        resultModel.show(_bookList,1),
                      ],
                    ],
                  )
              ),
            ),
            TextButton(
              onPressed: () {},
              autofocus: true,
              focusNode: _focusNode2,
              child: const Text(''),
            )
          ],
        )
    );
  }
}